<template>
  <div class="container cart-cont">
    <template v-if="!getCustomerId">
      <get-user-info v-if="isGetUserInfo" @updateUserInfo="initMemberInfo"></get-user-info>
    </template>
    <div v-if="listData.length">
      <div v-for="(item, index) in listData" :key="index" class="panel">
        <van-swipe-cell :right-width="64" @close="onClose(item,$event)" async-close>
          <div class="flex pad-t-12 pad-b-12 pad-r-8" @click.stop.prevent="goDetail(item)">
            <div class="check-box-l" @click.stop.prevent="onChangeOneSel(item, index)">
              <van-checkbox
                :disabled="item.disabledFlag"
                :value="item.show"
                :checked-color="getAppInfo.style.color2"></van-checkbox>
            </div>
            <div class="mar-l-7 goods-img-box pos-rel">
              <!-- 跨境图标 -->
              <div class="cross-border-pic">
                <!-- 跨境保税 -->
                <img
                  v-if="fileSpace && item.crossBorderType === 2 && item.crossBorderLabelType === 1"
                  :src="fileSpace + '/images/icon-cross-border.png'"
                  class="icon-cross-border"
                  alt="">
                <!-- 海外直邮 -->
                <img
                  v-if="fileSpace && item.crossBorderType === 2 && item.crossBorderLabelType === 2"
                  :src="fileSpace + '/images/icon-cross-border-22.png'"
                  class="icon-cross-border"
                  alt="">
              </div>
              <img class="width-100 height-100 border-radius-10" :src='item.goodsImage'/>
            </div>
            <div class="flex-item pad-t-1">
              <div class="flex flex-col flex-between min-h-c">
                <div class="width-per-100">
                  <div class="flex line-1 font-14 font-color font-w title-c-g">{{ item.goodsTitle }}</div>
                  <div class="goods-prop line-1 font-11 mar-t--1" v-if="item.skuDetail">{{ item.skuDetail }}</div>
                </div>
                <div class="width-per-100">
                  <!-- totalLimitNum  总限购数量 -->
                  <!-- limitNum  还可购买数量 -->
                  <div class="limit-box font-12 flex" v-if="item.totalLimitNum">
                    <span class="limit-info">
                      限购{{item.totalLimitNum}}件&nbsp;|&nbsp;还能买{{item.limitNum}}件
                      <span class="tag"></span>
                    </span>
                  </div>
                </div>
                <div class="width-per-100">
                  <div class="flex v-align-b">
                    <div class="flex-item">
                      <!-- 商品设置会员价处理；有会员价展示权限高于普通正常价格 -->
                      <div class="red-color font-20">
                        <span class="font-11">¥</span>{{ item.bestPrice }}
                      </div>
                      <div class="font-color-9 font-11 font-line-mid mar-t--7 mar-b--3" v-if="item.scribingPrice && (item.scribingPrice * 1 > 0)">
                        ¥{{ item.scribingPrice }}
                      </div>
                    </div>
                    <div class="count-box">
                      <van-stepper
                        v-if="item.goodsType !== 10"
                        :max="item.groupLimitNum"
                        :value="item.goodsNum"
                        @click.stop.prevent=""
                        @change="onChangeGoodsNum($event, index, 'effective', item)"/>
                      <van-stepper
                        v-else
                        :value="item.goodsNum"
                        @click.stop.prevent=""
                        @change="onChangeGoodsNum($event, index, 'effective', item)"/>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div slot="right">删除</div>
        </van-swipe-cell>
      </div>
    </div>
    <div v-for="(item, index) in promotionList" :key="index" class="panel">
      <div class="height-39 border-b v-align-c font-12">
        <div class="shipping-icon">包邮</div>
        <div class="mar-l-7 font-w">满{{item.fullPrice}}元包邮</div>
      </div>
      <div class="shipping-goods" v-for="(goods, goodsIndex) in item.feeGoodsList" :key="goodsIndex">
        <van-swipe-cell :right-width="54" @close="onClose(goods,$event)" async-close>
          <div class="flex pad-t-12 pad-b-12 pad-r-8" @click.stop.prevent="goDetail(goods)">
            <div class="check-box-l" @click.stop.prevent="onChangeTwoSel(goods, goodsIndex)">
              <van-checkbox
                :disabled="goods.disabledFlag"
                :value="goods.show"
                :checked-color="getAppInfo.style.color2"></van-checkbox>
            </div>
            <div class="mar-l-7 goods-img-box pos-rel">
              <!-- 跨境图标 -->
              <div class="cross-border-pic">
                <!-- 跨境保税 -->
                <img
                  v-if="fileSpace && goods.crossBorderType === 2 && goods.crossBorderLabelType === 1"
                  :src="fileSpace + '/images/icon-cross-border.png'"
                  class="icon-cross-border"
                  alt="">
                <!-- 海外直邮 -->
                <img
                  v-if="fileSpace && goods.crossBorderType === 2 && goods.crossBorderLabelType === 2"
                  :src="fileSpace + '/images/icon-cross-border-22.png'"
                  class="icon-cross-border"
                  alt="">
              </div>
              <img :src='goods.goodsImage' class="width-100 height-100 border-radius-10"/>
            </div>
            <div class="flex-item pad-t-1">
              <div class="flex flex-col flex-between min-h-c">
                <div class="width-per-100">
                  <div class="flex line-1 font-14 font-color font-w title-c-g">{{ goods.goodsTitle }}</div>
                  <div class="goods-prop line-1 font-11 mar-t--1" v-if="goods.skuDetail">{{ goods.skuDetail }}</div>
                </div>
                <div class="width-per-100">
                  <div class="limit-box font-12 flex" v-if="goods.totalLimitNum">
                    <span class="limit-info">
                      限购{{goods.totalLimitNum}}件&nbsp;|&nbsp;还能买{{goods.limitNum}}件
                      <span class="tag"></span>
                    </span>
                  </div>
                </div>
                <div class="width-per-100">
                  <div class="flex v-align-b">
                    <div class="flex-item">
                      <!-- 商品设置会员价处理；有会员价展示权限高于普通正常价格 -->
                      <div class="red-color font-20">
                        <span class="font-11">¥</span>{{ goods.bestPrice }}
                      </div>
                      <div class="font-color-9 font-11 font-line-mid mar-t--7 mar-b--3" v-if="goods.scribingPrice && (goods.scribingPrice * 1 > 0)">
                        ¥{{ goods.scribingPrice }}
                      </div>
                    </div>
                    <div class="count-box">
                      <van-stepper
                        v-if="goods.goodsType !== 10"
                        :max="goods.groupLimitNum"
                        :value="goods.goodsNum"
                        @click.stop.prevent=""
                        @change="onChangeGoodsNum($event, goodsIndex, 'promotion', goods)"/>
                      <van-stepper
                        v-else
                        :value="goods.goodsNum"
                        @click.stop.prevent=""
                        @change="onChangeGoodsNum($event, goodsIndex, 'promotion', goods)"/>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div slot="right">删除</div>
        </van-swipe-cell>
      </div>
    </div>
    <!-- 失效商品 -->
    <template v-if="listFailData.length !== 0">
      <div class="flex flex-between panel-subject">
        <span class="font-16 font-color-3 font-w">已失效商品</span>
        <span class="red-color font-14" @click="clearNoEffect">清空失效商品</span>
      </div>
      <div>
        <div v-for="(item, index) in listFailData" :key="index" class="panel">
          <van-swipe-cell :right-width="54" @close="onClose(item,$event)" async-close>
            <div class="flex pad-t-12 pad-b-12 pad-r-8">
              <div class="fail-tag-box mar-r-9 font-color-9 ">
                <div class="font-12">失效</div>
              </div>
              <div class="mar-r-9">
                <img :src='item.goodsImage' class="img-item width-100 height-100 border-radius-10" />
              </div>
              <div class="flex-item">
                <div class="flex">
                  <div class="flex-item line-1 font-14 font-w font-color-9">{{ item.goodsTitle }}</div>
                </div>
              </div>
            </div>
            <div slot="right">删除</div>
          </van-swipe-cell>
        </div>
      </div>
    </template>
    <!-- 合计 -->
    <div class="flex v-align-c bottom-btn">
      <div class="v-align-c mar-t--4" @click="onCheckAll">
        <van-checkbox :value="checkAll" :checked-color="getAppInfo.style.color2">
          全选
        </van-checkbox>
      </div>
      <div class="flex v-align-c flex-item">
        <div class="font-12 font-color-3 mar-r-12">
          <span>合计：</span>
          <label class="font-color font-18 font-w"><span class="font-11">¥ </span>{{ total }}</label>
        </div>
        <div
          v-if="!isDelBtn"
          class="submit width-92 height-38"
          @click="settlement">
          <div
            class="flex flex-center submit-btn font-14 width-per-100 height-per-100"
            :class="number ? 'submit-btn': 'dis-submit-btn'">
          去结算({{number}})</div>
        </div>
        <div v-else class="submit width-92 height-38" @click="batchDelete(selCartList)">
          <div class="flex flex-center delete-btn font-14 width-per-100 height-per-100">
          删除</div>
        </div>
      </div>
    </div>
    <!-- 跨境分开结算层 -->
    <van-popup
      :show="showCrossBorder"
      :safe-area-inset-bottom="false"
      catchtouchmove="true"
      position="bottom"
      @close="closeCrossBorder">
      <div class="cb-l-title flex flex-center height-48">
        <h2>请分开结算以下商品</h2>
        <div class="cb-l-close" @click="closeCrossBorder">
          <img
            v-if="fileSpace"
            :src="fileSpace + '/images/icon-close-layer.png'"
            class="width-15 height-15"
            alt="">
        </div>
      </div>
      <div class="height-48"></div>
      <div class="cb-l-main">
        <scroll-view scroll-y="" class="clearfix scroll-main">
          <div class="pad-l-15 pad-r-15">
            <ul class="cb-l-list">
              <li
                v-for="(itemL, indexL) in cbListData"
                :key="indexL">
                <div v-if="itemL.warehouseType === 1" class="flex v-align-c pad-t-6 pad-b-9">
                  <img
                    v-if="fileSpace"
                    :src="fileSpace + '/images/icon-cross-border-s1.png'"
                    class="width-21 height-19 mar-r-7"
                    alt="">
                  <h3 class="font-normal">{{ itemL.warehouseName }}</h3>
                </div>
                <div v-else class="flex v-align-c pad-t-6 pad-b-9">
                  <img
                    v-if="fileSpace"
                    :src="fileSpace + '/images/icon-cross-border-s2.png'"
                    class="width-21 height-19 mar-r-7"
                    alt="">
                  <h3 class="font-normal">{{ itemL.warehouseName }}</h3>
                </div>
                <div class="flex v-align-c" @click="detailCrossBorder(itemL)">
                  <span v-for="(itemG, indexG) in itemL.shoppingCartList" :key="indexG">
                    <img
                      v-if="itemG.goodsImage"
                      :src="itemG.goodsImage"
                      class="width-50 height-50 border-radius-5 mar-r-8"
                      alt="">
                  </span>
                  <div
                    v-if="itemL.shoppingCartList && itemL.shoppingCartList.length > 4"
                    class="cb-l-all flex flex-center border-radius-5 width-50 height-50 font-12">
                    <span>全部</span>
                  </div>
                </div>
                <div class="flex v-align-b pad-t-13 pad-b-13">
                  <div class="flex-item">
                    <div class="font-13 pad-b-3">
                      共{{ itemL.goodsTotalNum }}件商品，合计：
                      <span class="font-12 font-color-money">¥ </span>
                      <span class="font-18 font-w font-color-money">{{ itemL.totalPayAmount }}</span>
                    </div>
                    <div v-if="itemL.warehouseType === 1" class="font-13">(不含运费)</div>
                    <div v-else class="font-13">(含进口税，不含运费)</div>
                  </div>
                  <!-- :class="indexL === 1 ? 'submit-btn': 'dis-submit-btn'" -->
                  <div
                    @click="splitSettlement(itemL)"
                    class="settlement-s flex flex-center height-34 font-14 pad-l-20 pad-r-20 mar-b-3">
                    <span>去结算</span>
                  </div>
                </div>
              </li>
            </ul>
          </div>
        </scroll-view>
      </div>
    </van-popup>
    <!-- 跨境详情商品层 -->
    <van-popup
      :show="showDetailCrossBorder"
      :safe-area-inset-bottom="false"
      catchtouchmove="true"
      :overlay="false"
      position="bottom"      
      @close="closeDetailCrossBorder">
      <div class="cb-l-title flex flex-center height-48">
        <h2>商品信息</h2>
        <div class="cb-l-close" @click="closeDetailCrossBorder">
          <img
            v-if="fileSpace"
            :src="fileSpace + '/images/icon-close-layer.png'"
            class="width-15 height-15"
            alt="">
        </div>
      </div>
      <div class="height-48"></div>
      <div class="cb-l-main">
        <scroll-view scroll-y="" class="clearfix scroll-main">
          <div class="pad-l-15 pad-r-15">
            <ul class="cb-l-list">
              <li
                v-for="(itemL, indexL) in cbItemData"
                :key="indexL"
                class="flex v-align-t pad-t-11 pad-b-12">
                <img
                  v-if="fileSpace && itemL.goodsImage"
                  :src="itemL.goodsImage"
                  class="width-80 height-80 border-radius-10 mar-r-8"
                  alt="">
                <div class="flex-item">
                  <div class="pad-t-2"></div>
                  <h4 class="font-normal font-16 detail-cb-title">{{ itemL.goodsTitle }}</h4>
                  <div class="flex v-align-b pad-t-28">
                    <div class="flex-item font-12 font-color-9">
                      <div>单价：￥{{ itemL.bestPrice }}</div>
                      <div class="mar-t--4">数量：{{ itemL.goodsNum }}</div>
                    </div>
                    <div class="font-16 font-w font-color-money mar-b--2"><span class="font-11">¥ </span>{{ itemL.goodsSubTotalAmount }}</div>
                  </div>
                </div>
              </li>
            </ul>
          </div>
        </scroll-view>
      </div>
    </van-popup>
    <!-- 空空如也 -->
    <div
      v-if="(listData.length===0 && isInitDone && listFailData.length===0 && promotionList.length===0)  || !getCustomerId"
      class="align-c mar-t-30 pad-30">
      <img v-if="fileSpace" mode="widthFix" class="width-153 height-75 mar-t-30" :src="fileSpace + '/images/2-0-kong.png'" />
      <div class="pad-t-20 font-14 font-gray">空空如也</div>
    </div>
    <!-- 回我店铺 -->
    <div class="fix-r-btn flex-col">      
      <div class="align-r pad-r-13">
        <back-btn />
      </div>
    </div>
  </div>
</template>

<script>
import GetUserInfo from '@/components/GetUserInfo'
import { deleteShoppingCart, updateShoppingCart, getShopCartVeekray, batchDelete, isOrderCheck } from '@/api/shop'
import { getMemberInfo } from '@/api/home'
import { setStoreCardFlag, setMemberNature, setShowBuyCard, setCartBadge } from '@/utils/auth'
import { getAuth } from '@/api/login'
import { appColor } from '@/api/appColor'
import { getAppInfo } from '@/api/common'
import BackBtn from '@/components/BackBtn'

export default {
  components: { GetUserInfo, BackBtn },
  data() {
    return {
      isGetUserInfo: false,
      checkAll: false,
      listData: [],
      storeHomeGoodsList: [], // 门店自提商品
      listFailData: [],
      listQuery: {
        memberId: '',
        customerId: '',
        enterpriseId: ''
      },
      isInitDone: false,
      selCartList: [],
      selCartData: [],
      allCartList: [],
      goodsType: null,
      shareMemberId: '',
      number: 0,
      statusList: ['快递配送', '门店自提'],
      activeIndex: 0,
      type: null,
      memberInfo: {},
      customerInfo: {},
      spaceBarHeight: 0,
      promotionList: [], // 包邮活动商品数组
      fastGoods: [],
      getAppInfo: {},
      navList: [],
      isDelBtn: false, // 是否是删除按钮状态  false: 结算按钮
      listType: '', // 商品类型，1: '快递发货', 3: '社区团购', 4: '到家自提', 5: '配送到家' （从购物车进入时需要携带这个参数）
      showCrossBorder: false,
      showDetailCrossBorder: false,
      cbListData: [],
      cbItemData: []
    }
  },
  computed: {
    isIPhoneX() {
      return this.$utils.isIPhoneX()
    },
    total() {
      let total = 0
      let totalPro = 0
      this.listData.forEach((item, index) => {
        this.selCartList.forEach((selItem, selIndex) => {
          if (item.cartId === selItem) {
            total = (total * 1 + item.bestPrice * item.goodsNum).toFixed(2)
          }
        })
      })
      if (this.promotionList.length !== 0) {
        this.promotionList.forEach((itemOne, indexOne) => {
          itemOne.feeGoodsList.forEach((subItem, subIndex) => {
            this.selCartList.forEach((selItem, selIndex) => {
              if (subItem.cartId === selItem) {
                totalPro = (totalPro * 1 + subItem.bestPrice * subItem.goodsNum).toFixed(2)
              }
            })
          })
        })
      }
      if (!this.$utils.isNumber(total)) total = 0
      return (Math.round(total * 100) / 100 + Math.round(totalPro * 100) / 100).toFixed(2)
    }
  },
  onLoad() {
    // 初始化data
    Object.assign(this.$data, this.$options.data())
    this.getAppInfo = this.$pt.getStorageSync('appInfo')
    this.memberInfo.avatar = 'https://veekrayimg.joinsun.vip/head-portrait.png'
    this.customerInfo.avatar = 'https://veekrayimg.joinsun.vip/head-portrait.png'
    this.getAuth()
  },
  // onReady() {
  //   this.init()
  // },
  mounted() {
    this.init()
  },
  onShow() {
    this.init()
    // 清除分类缓存分类ID
    this.$pt.removeStorageSync('categoryInfo')
  },
  methods: {
    closeDetailCrossBorder() {
      this.showDetailCrossBorder = false
    },
    closeCrossBorder() {
      this.showCrossBorder = false
    },
    detailCrossBorder(item) {
      this.showDetailCrossBorder = true
      if (item.shoppingCartList && item.shoppingCartList.length) {
        this.cbItemData = []
        this.cbItemData = item.shoppingCartList
      }
    },
    init() {
      console.log('cart init')
      this.spaceBarHeight = this.$pt.getSystemInfoSync()['statusBarHeight'] + 44 + 36
      this.getAppEls()
      this.activeIndex = 0
      if (this.getMemberId) {
        this.initMemberInfo()
        this.shareMemberId = this.getCurrentPage().query.shareMemberId
        this.selCartList = []
        this.selCartData = []
        this.allCartList = []
        this.number = 0
        this.checkAll = false
        this.listQuery.memberId = this.getMemberId
        this.listQuery.customerId = this.getCustomerId
        this.listQuery.enterpriseId = this.getEnterpriseId ? this.getEnterpriseId : ''
        if (this.getCustomerId) {
        // this.listQuery.customerId = this.getMemberId
          this.getShopCartVeekray()
        }
      }
    },
    getAppEls() {
      getAppInfo().then((response) => {
        if (response.isError) return
        let getAppInfo = response.data
        this.getAppInfo = appColor(getAppInfo)
      }).catch(() => {
      })
    },
    getAuth() {
      this.$pt.login({
        success(res) {
          if (res.code) {
            getAuth(res.code).then((response) => {
              setShowBuyCard(response.data.showBuyCard)
            }).catch(() => {
            })
          }
        }
      })
    },
    // 会员基本信息
    initCustomerInfo() {
      getMemberInfo(this.getCustomerId).then((response) => {
        if (response.isError) return
        this.customerInfo = response.data
        setTimeout(() => {
          if (this.customerInfo.nickname) {
            this.customerInfo.nickname = this.$utils.getStrByLens(this.customerInfo.nickname, 16)
          }
          if (this.customerInfo.memberDetails.personalityName) {
            this.customerInfo.memberDetails.personalityName = this.$utils.getStrByLens(this.customerInfo.memberDetails.personalityName, 30)
          }
          if (!this.getCustomerId) {
            this.customerInfo.avatar = 'https://veekrayimg.joinsun.vip/head-portrait.png'
          }
        }, 500)
      }).catch(() => {
      })
    },
    initMemberInfo() {
      if (this.getCustomerId) {
        this.initCustomerInfo()
      }
      getMemberInfo(this.getMemberId).then((response) => {
        if (response.isError) return
        this.memberInfo = response.data
        if (response.data.storeCardFlag) {
          setStoreCardFlag(response.data.storeCardFlag)
        }
        if (response.data.nature) {
          setMemberNature(response.data.nature)
        }
        // 名片模版
        if (this.memberInfo.cardTemp) {
          this.cardTemp = this.memberInfo.cardTemp
        }
        setTimeout(() => {
          if (this.memberInfo.nickname) {
            this.memberInfo.nickname = this.$utils.getStrByLens(this.memberInfo.nickname, 16)
          }
          if (this.memberInfo.memberDetails.personalityName) {
            this.memberInfo.memberDetails.personalityName = this.$utils.getStrByLens(this.memberInfo.memberDetails.personalityName, 30)
          }
        }, 500)
      }).catch(() => {
      })
    },
    tabClick(e) {
      let index = e.mp.detail.index
      this.activeIndex = index
      if (this.getCustomerId) {
        this.getShopCartVeekray()
      }
    },
    // 判断两个数组相等
    compareArraySort(a1, a2) {
      if ((!a1 && a2) || (a1 && !a2)) return false
      if (a1.length !== a2.length) return false
      a1 = [].concat(a1)
      a2 = [].concat(a2)
      a1 = a1.sort()
      a2 = a2.sort()
      for (var i = 0, n = a1.length; i < n; i++) {
        if (a1[i] !== a2[i]) return false
      }
      return true
    },
    getShopCartVeekray() {
      this.isInitDone = false
      this.listData = []
      this.selCartList = []
      this.selCartData = []
      this.allCartList = []
      this.listFailData = []
      this.promotionList = []
      this.number = 0
      if (!this.getShowBuyCard) {
        this.listQuery.customerId = this.getMemberId
      }
      getShopCartVeekray(this.listQuery).then(response => {
        if (response.isError) return
        this.$pt.hideToast()
        let number = 0
        if (response.data.expressFlag === 1 && response.data.pickUpFlag === 1) {
          this.type = 3
        }
        if (response.data.expressFlag === 1 && response.data.pickUpFlag === 0) {
          this.type = 1
        }
        if (response.data.expressFlag === 0 && response.data.pickUpFlag === 1) {
          this.type = 2
        }
        if (response.data.promotionList) {
          this.promotionList = response.data.promotionList
          number += this.promotionList.length
        } else {
          this.promotionList = []
        }
        if (this.promotionList.length !== 0 && this.activeIndex === 0) {
          this.setGroupMaxNum(this.promotionList)
          this.allCartList = []
          this.promotionList.forEach(itemOne => {
            if (itemOne.feeGoodsList) {
              itemOne.feeGoodsList.forEach(subItem => {
                subItem.show = false
                if (!subItem.disabledFlag) {
                  this.allCartList.push(subItem.cartId)
                }
              })
            } else {
              itemOne.feeGoodsList = []
            }
          })
        }
        if (this.activeIndex === 1) {
          this.promotionList = []
        }
        let listRes = response.data.effectiveList
        number += listRes.length
        this.listFailData = response.data.noEffectiveList // 失效商品
        this.listData = []
        this.sendGoodsNumber(number)
        this.storeHomeGoodsList = []
        this.$pt.removeStorageSync('fastGoods')
        this.fastGoods = []
        listRes.forEach(item => {
          this.listData.push(item)
        })
        if (this.listData.length) {
          this.setGroupMaxNum(this.listData)
        }
        this.listData.forEach(item => {
          if (!item.disabledFlag) {
            this.allCartList.push(item.cartId)
          }
        })
        let allEffectiveList = []
        let promotionList = []
        this.promotionList.forEach(item => {
          item.feeGoodsList.forEach(itemSub => {
            promotionList.push(itemSub)
          })
        })
        allEffectiveList = listRes.concat(promotionList)
        if (allEffectiveList.length) {
          allEffectiveList.forEach((item, index) => {
            // 重新获取快速购买数据
            if (item.skuId) {
              // 多规格
              let skuData = []
              let objSkuData = {
                skuId: item.skuId,
                goodsNum: item.goodsNum,
                bestPrice: item.bestPrice
              }
              skuData.push(objSkuData)
              let goodsNum = null
              skuData.forEach(item => {
                goodsNum += item.goodsNum
              })
              this.fastGoods.push({
                goodsId: item.goodsId,
                skuFlag: 1,
                skuList: skuData,
                goodsNum: goodsNum
              })
            } else {
              // 单规格
              let objFastGoods = {
                goodsId: item.goodsId,
                skuFlag: 0,
                goodsNum: item.goodsNum,
                bestPrice: item.bestPrice
              }
              this.fastGoods.push(objFastGoods)
            }
          })
        }
        let map = {}
        let dest = []
        this.fastGoods.forEach(item => {
          if (!map[item.goodsId]) {
            if (item.skuFlag) {
              dest.push({
                goodsId: item.goodsId,
                goodsNum: item.goodsNum,
                skuFlag: 1,
                skuList: item.skuList
              })
            } else {
              let objDest = {
                goodsId: item.goodsId,
                goodsNum: item.goodsNum,
                skuFlag: 0,
                bestPrice: item.bestPrice
              }
              dest.push(objDest)
            }
            map[item.goodsId] = item
          } else {
            dest.forEach(itemSub => {
              if (itemSub.goodsId === item.goodsId) {
                itemSub.goodsNum = itemSub.goodsNum + item.goodsNum
                itemSub.skuList = itemSub.skuList.concat(item.skuList)
              }
            })
          }
        })
        this.fastGoods = []
        this.fastGoods = dest
        // 重新获取购物车角标数
        this.resetBadgeEls()
        this.allCartList = this.allCartList.sort(this.sortNumber)
        this.isInitDone = true
        this.checkAll = false
      }).catch(() => {
      })
    },
    setGroupMaxNum(list) {
      if ('feeGoodsList' in list[0]) {
        // 包邮商品
        let arrData = []
        list.forEach(item => {
          if (item.feeGoodsList && item.feeGoodsList.length) {
            item.feeGoodsList.forEach(itemSub => {
              arrData.push(itemSub)
            })
          }
        })
        this.setLimitNumEls(arrData)
      } else {
        // 非包邮商品
        this.setLimitNumEls(list)
      }
    },
    setLimitNumEls(list) {
      list.forEach(item => {
        // item.totalLimitNum = 5
        // item.limitNum = 0
        item.disabledFlag = false
        if (item.totalLimitNum > 0) {
          if ((item.goodsNum > item.limitNum) && item.limitNum) {
            item.disabledFlag = true
            item.groupLimitNum = item.goodsNum
          } else if (item.limitNum === 0) {
            item.disabledFlag = true
            item.groupLimitNum = item.limitNum
          } else {
            item.groupLimitNum = item.limitNum
            this.$set(item, 'disabledFlag', false)
          }
        } else {
          item.groupLimitNum = item.stock
          this.$set(item, 'disabledFlag', false)
        }
        const changeData = item.groupLimitNum
        this.$delete(item, 'groupLimitNum')
        this.$set(item, 'groupLimitNum', changeData)
        const disabledData = item.disabledFlag
        this.$delete(item, 'disabledFlag')
        this.$set(item, 'disabledFlag', disabledData)
      })
    },
    sendGoodsNumber(res) {
      this.$emit('getGoodsNumber', res)
    },
    // 编辑/完成
    editGoods() {
      this.isDelBtn = !this.isDelBtn
    },
    resetBadgeEls() {
      if (this.fastGoods.length) {
        let cartBadge = 0
        this.fastGoods.forEach(itemGoods => {
          cartBadge += itemGoods.goodsNum
        })
        if (this.cartIndexEls()) {
          this.$pt.setTabBarBadge({
            index: this.cartIndexEls(),
            text: String(cartBadge)
          })
          setCartBadge(cartBadge)
        }
      } else {
        this.$pt.removeStorageSync('cartBadge')
        this.$pt.removeTabBarBadge({
          index: this.cartIndexEls()
        })
      }
    },
    // 普通商品
    onChangeOneSel(item, index) {
      if (item.disabledFlag) return
      // 判断是否能一起结算
      if (item.show) {
        // 计划取消勾选
        this.selCartList.forEach((selItem, selIndex) => {
          if ((selItem === item.cartId) && !item.disabledFlag) {
            this.selCartList.splice(selIndex, 1)
          }
        })
      } else {
        // 计划勾选
        if (!item.disabledFlag) {
          this.selCartList.push(item.cartId)
        }
      }
      item.show = !item.show
      this.number = this.selCartList.length
      if (this.compareArraySort(this.allCartList, this.selCartList)) {
        this.checkAll = true
      } else {
        this.checkAll = false
      }
    },
    onChangeTwoSel(item, index) {
      // 判断是否能一起结算
      if (item.show) {
        this.selCartList.forEach((selItem, selIndex) => {
          if ((selItem === item.cartId) && !item.disabledFlag) {
            this.selCartList.splice(selIndex, 1)
          }
        })
      } else {
        if (!item.disabledFlag) {
          this.selCartList.push(item.cartId)
        }
      }
      item.show = !item.show
      this.number = this.selCartList.length
      if (this.compareArraySort(this.allCartList, this.selCartList)) {
        this.checkAll = true
      } else {
        this.checkAll = false
      }
    },
    onChangeGoodsNum(e, index, type, currentItem) {
      const shoppingCart = {
        cartId: '',
        goodsNum: 0
      }
      shoppingCart.cartId = currentItem.cartId
      if ((currentItem.goodsNum > currentItem.limitNum) && currentItem.limitNum) {
        currentItem.disabledFlag = true
        const disabledData = currentItem.disabledFlag
        this.$delete(currentItem, 'disabledFlag')
        this.$set(currentItem, 'disabledFlag', disabledData)
        currentItem.groupLimitNum = currentItem.limitNum
        currentItem.goodsNum = currentItem.limitNum
        shoppingCart.goodsNum = currentItem.limitNum
        this.allCartList.push(currentItem.cartId)
      } else {
        currentItem.goodsNum = e.mp.detail
        shoppingCart.goodsNum = currentItem.goodsNum
      }
      updateShoppingCart(shoppingCart).then((response) => {
        if (response.isError) return false
        this.fastGoods.forEach(item => {
          if (item.goodsId === currentItem.goodsId) {
            if (currentItem.skuId) {
              let goodsNum = null
              item.skuList.forEach(itemSku => {
                if (itemSku.skuId === currentItem.skuId) {
                  itemSku.goodsNum = shoppingCart.goodsNum
                  itemSku.bestPrice = currentItem.bestPrice
                }
                goodsNum += itemSku.goodsNum * 1
              })
              item.goodsNum = goodsNum * 1
            } else {
              item.goodsNum = shoppingCart.goodsNum * 1
              item.bestPrice = currentItem.bestPrice
            }
          }
        })
        // 重新获取购物车角标数
        this.resetBadgeEls()
      }).catch(() => {
      })
    },
    // 全选/反选
    onCheckAll() {
      // 判断是否能全选
      if (this.checkAll) {
        // 计划取消全选
        if (this.listData.length !== 0) {
          this.listData.forEach(item => {
            item.show = false
          })
        }
        if (this.promotionList.length !== 0) {
          this.promotionList.forEach(itemOne => {
            itemOne.feeGoodsList.forEach(subItem => {
              subItem.show = false
            })
          })
        }
        this.selCartList = []
        this.number = 0
      } else {
        // 计划全选
        this.selCartList = []
        if (this.listData.length !== 0) {
          this.listData.forEach(item => {
            if (!item.disabledFlag) {
              item.show = true
              this.selCartList.push(item.cartId)
            }
          })
        }
        if (this.promotionList.length !== 0) {
          this.promotionList.forEach(itemOne => {
            itemOne.feeGoodsList.forEach(subItem => {
              if (!subItem.disabledFlag) {
                subItem.show = true
                this.selCartList.push(subItem.cartId)
              }
            })
          })
        }
        this.number = this.selCartList.length
      }
      this.checkAll = !this.checkAll
    },
    cartIndexEls() {
      let cartIndex = null
      this.navList = this.$pt.getStorageSync('navList')
      if (this.navList.length) {
        this.navList.forEach((item, index) => {
          if (item.linkType === 1007) {
            cartIndex = index
          }
        })
      } else {
        cartIndex = 2
      }
      return cartIndex
    },
    showFastNum(item) {
      let cartBadge = 0
      this.fastGoods.forEach(itemGoods => {
        if (itemGoods.goodsId === item.goodsId) {
          item.selShow = true
          if (itemGoods.skuFlag) {
            item.goodsNum = itemGoods.goodsNum
          } else {
            item.goodsNum = itemGoods.goodsNum
          }
        }
        cartBadge += itemGoods.goodsNum
      })
      if (this.cartIndexEls()) {
        this.$pt.setTabBarBadge({
          index: this.cartIndexEls(),
          text: String(cartBadge)
        })
      }
    },
    resetData() {
      // 物流商品数据重置
      this.selCartList = []
      this.selCartData = []
    },
    // 删除失效商品
    clearNoEffect() {
      if (this.listFailData.length) {
        let listFailData = []
        this.listFailData.forEach(item => {
          listFailData.push(item.cartId)
        })
        this.batchDelete(listFailData)
      }
    },
    // 可批量删除商品
    batchDelete(list) {
      if (!list.length) {
        this.$utils.showToast({ title: '购物车内还未选中商品' })
        return
      }
      const that = this
      this.$pt.showModal({
        content: '确定要删除此商品吗？',
        success(res) {
          if (res.confirm) {
            batchDelete(list).then((response) => {
              if (response.isError) return
              that.$utils.showToast({ title: '删除成功' })
              that.$emit('changeEditBtnText')
              that.isDelBtn = false
              setTimeout(() => {
                that.getShopCartVeekray()
                that.resetData()
              }, 500)
            }).catch(() => {
            })
          } else if (res.cancel) {
            console.log('用户取消')
            that.$emit('changeEditBtnText')
            that.isDelBtn = false
            // that.resetData()
          }
        }
      })
    },
    deleteShoppingCart(value) {
      const that = this
      this.$pt.showModal({
        content: '确定要删除此商品吗？',
        success(res) {
          if (res.confirm) {
            deleteShoppingCart(value.cartId).then((response) => {
              if (response.isError) return
              that.$utils.showToast({ title: '删除成功' })
              setTimeout(() => {
                that.getShopCartVeekray()
              }, 500)
              if (!that.fastGoods.length) return
              that.fastGoods.forEach((itemGoods, indexGoods) => {
                if (itemGoods.goodsId === value.goodsId) {
                  // 已存在商品
                  that.fastGoods.splice(indexGoods, 1)
                }
              })
              // 后期需优化模块
              let cartBadge = 0
              that.fastGoods.forEach((itemGoods, indexGoods) => {
                cartBadge += itemGoods.goodsNum
              })
              that.$pt.setTabBarBadge({
                index: that.cartIndexEls(),
                text: String(cartBadge)
              })
              setCartBadge(cartBadge)
            }).catch(() => {
            })
          } else if (res.cancel) {
            console.log('用户取消')
          }
        }
      })
    },
    // 是否有选中的商品
    ifSelCart() {
      let selCart = false
      this.selCartList.forEach((item) => {
        if (item) selCart = true
      })
      return selCart
    },
    // 订单校验（是否含有跨境商品）
    isOrderCheck() {
      let params = {
        fromType: '',
        memberId: this.getMemberId,
        customerId: this.getCustomerId,
        goodsId: '',
        cartIds: [],
        skuId: '',
        goodsNum: '',
        addressId: '',
        deliveryType: this.listType
      }
      // 购物车类型，cartIds有数据时， fromType = 3；
      // 自营商品（goodsType === 10），fromType = 1
      // 分销商品、零售商品（goodsType === 30 || goodsType === 31 || goodsType === 32），fromType = 2
      params.fromType = 3
      params.cartIds = this.selCartList
      return isOrderCheck(params)
    },
    // 去结算
    settlement() {
      // console.log(this.selCartList)
      // this.listType 商品类型；   1: '快递发货', 3: '社区团购', 4: '到家自提', 5: '配送到家' （从购物车进入时需要携带这个参数）
      this.listType = 1
      this.isOrderCheck().then(res => {
        if (res.code === 2000 && res.data && res.data.length) {
          // 含有跨境分开流程
          this.cbListData = res.data
          // 跨境分开结算弹窗层
          this.showCrossBorder = true
        } else if (res.code === 101) {
          this.toBuyPage(this.selCartList)
        }
      })
    },
    toBuyPage(arrData) {
      let selCartList = []
      selCartList = arrData
      // 只存在普通物流快递商品; 或者跨境是同一个保税仓
      if (selCartList.length === 0) {
        return
      }
      if (!this.ifSelCart()) {
        return this.$utils.showToast({ title: '请选择要结算的商品' })
      } else {
        if (this.shareMemberId) {
          this.$pt.navigateTo({
            url: '/pages/shop/buy/main?cartIds=' + selCartList + '&shareMemberId=' + this.shareMemberId
          })
        } else {
          this.$pt.navigateTo({
            url: '/pages/shop/buy/main?cartIds=' + selCartList
          })
        }
      }
    },
    splitSettlement(item) {
      this.toBuyPage(item.cartIds)
      this.closeCrossBorder()
    },
    onClose(value, event) {
      // 滑动单元格关闭事件
      const { position, instance } = event.mp.detail
      switch (position) {
        // 点击中间部分触发的事件
        case 'cell':
          instance.close()
          break
        case 'right':
          // 点击滑块右边触发的事件 (删除)
          this.deleteShoppingCart(value)
          instance.close()
          break
      }
    },
    goDetail(item) {
      this.$pt.navigateTo({ url: `/pages/shop/detail/main?goodsId=${item.goodsId}&goodsType=${item.goodsType}` })
    }
  }
}
</script>

<style lang="less" scoped>
.min-h-c{
  min-height: 99px;
}
.title-c-g{
  height: 20px;
  line-height: 20px;
}
.fix-r-btn{
  position: fixed;
  right: 0;
  bottom: 52px;
  z-index: 20;
}
.top-space{
    height: 64px;
  }
.container {
  .panel-subject {
    padding-left: 13px;
    padding-right: 12.5px;
    padding-bottom: 16px;
    padding-top: 10px;
  }
  .panel {
    box-shadow: 0 0 0;
    border-top: none;
    border-bottom: none;
    overflow: hidden;
    border-radius: 10px;
    margin-bottom: 12px;
    box-shadow: 0px 1px 9px 0px rgba(172, 172, 172, 0.22);
    padding-left: 7px;
    padding-top: 0px;
    padding-right: 0px;
    padding-bottom: 0px;
    .check-box-l {
      display: flex;
      align-items: center;
      padding-bottom: 10px;
    }
    .goods-img-box {
      margin-right: 9px;
    }
  }
  .bottom-btn {
    padding-top: 6px;
    padding-bottom: 6px;
    padding-left: 20px;
    padding-right: 12px;
    background: #fff;
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    box-sizing: border-box;
    border-radius: 10px 10px 0px 0px;
    &>div:nth-child(2) {
      justify-content: flex-end;
    }
    .submit {
      .submit-btn {
        background: #FF243D;
        border-radius: 50px;
        color: #fff;
    }
    .dis-submit-btn {
      background: #D6D6D6;
      color: #fff;
      border-radius: 50px;
    }
    .delete-btn {
      background: #fff;
      color: #FF243D;
      border-radius: 50px;
      border: 1px solid #FF243D;
    }
  }
  /deep/ .van-swipe-cell__right {
    background: #FF3A2F;
    height: 100%;
    top: 0;
    color: white;
    width: 100%;
    padding-left: 13px;
    display: flex;
    align-items: center;
  }
}
.count-box, .goods-total{
  /deep/ .van-stepper__minus, /deep/ .van-stepper__plus {
    width: 28px;
  }
}
.red-color {
  color: #FF243D;
}
}
.fail-bar {
  text-align: center;
  height: 20px;
  border-top: #c5c5c5 1px solid;
  margin-top: 25px;
  margin-bottom: 5px;
  .fail-text {
    display: block;
    background: #f5f5f5;
    color: #999999;
    width: 73px;
    height: 20px;
    margin: -6px auto 0 auto;
    text-align: center;
    line-height: 1;
  }
}
.fail-tag-box {
  display: flex;
  align-items: center;
  padding-bottom: 8px;
  .fail-tag {
    background: #4b4b4d;
    color: #fff;
    text-align: center;
    height: 17px;
    line-height: 17px;
    border-radius: 50px;
  }
}
.cart-tab {
  background: #fff;
  position: fixed;
  left: 0;
  top: 0px;
  width: 100%;
  z-index: 20;
  .cart-tab-bar {
    width: 195px;
    margin: 0 auto;
  }
}
.font-red {
  color: #ff0000;
}
.icon-iconfontshanchu2 {
  color: #333;
}
.panel {
  box-shadow: 0 0 0;
  border-top: none;
  border-bottom: none;
  overflow: hidden;
  border-radius: 8px;
  margin-bottom: 15px;
  box-shadow: 0px 1px 9px 0px rgba(172, 172, 172, 0.22);
  .check-box-l {
    display: flex;
    align-items: center;
    padding-bottom: 10px;
  }
  /deep/ .van-swipe-cell__right {
    background: #ff4a4a;
    height: 100%;
    top: 0;
    color: white;
    width: 100%;
    padding-left: 13px;
    display: flex;
    align-items: center;
  }
}
.goods-prop {
  // width: 173px;
  height: 18px;
  line-height: 18px;
  box-sizing: border-box;
  // padding: 0 5px;
  color: #b5b5b5;
  // background: #f2f2f2;
}

.img-item {
  border-radius: 10px;
  opacity: 0.5;
}

// .bottom-btn {
//   width: 100%;
//   height: 49px;
//   position: fixed;
//   bottom: 0;
//   background-color: #fff;
// }

// .submit {
//   padding: 0 10px 0 5px;
//   .submit-btn {
//     background: #ffe200;
//     border-radius: 50px;
//     color: #333;
//     padding: 0 15px;
//     height: 35px;
//     line-height: 35px;
//     font-size: 15px;
//   }
// }
.shipping-goods {
  &:last-child {
    .goods-info {
      border-bottom: unset;
    }
  }
  .goods-info {
    border-bottom: 1px solid #f6f6f6;
  }
}
.goods-content {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.goods-total {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  line-height: 1;
}
.shipping-icon {
  width: 29px;
  height: 16px;
  line-height: 16px;
  border-radius: 0 3px 3px;
  color: white;
  background: #ed4836;
  text-align: center;
}
.border-b {
  border-bottom: 1px solid #f6f6f6;
}
.limit-box {
  color: #00AA6B;
  // position: absolute;
  // top: -24px;
  .limit-info {
    background: #E5F7F1;
    border: 1px solid #CEEDE3;
    border-radius: 5px;
    padding-left: 3px;
    padding-right: 4px;
    padding-top: 1px;
    padding-bottom: 1px;
    position: relative;
    .tag {
      position: absolute;
      bottom: -4px;
      left: 14px;
      display: inline-block;
      width: 0;
      height: 0;
      border-top: 4px solid #E5F7F1;
      border-left: 6px solid transparent;
      border-right: 6px solid transparent;
    }
  }
}
._line-2 {
    line-height: 1.4;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    word-break: break-word;
}
</style>
